"""
@Author    : ghenyar
@Time      : 2025/9/8 10:42
@File      : menus
@Desc      :  菜单路由
"""
from functools import partial
from typing import Union

from fastapi import APIRouter, Security, Request, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.admin.decorator import log_operation
from app.admin.schemas.menus import MenuSchema
from app.admin.security import authority
from app.admin.service.menu_service import MenuService
from app.common.response import ApiResponse
from app.core.db import async_get_db

router = APIRouter()

# 鉴权
Auth = partial(Security, authority)

type_map = {1: "目录", 2: "菜单", 3: "按钮"}


@router.get("/lists", dependencies=[Auth(scopes=["menus:lists"])], response_model=ApiResponse)
async def menu_lists(db: AsyncSession = Depends(async_get_db)):
    """
    目录/菜单/权限列表
    :return:
    """
    result = await MenuService.lists(db)
    return ApiResponse.result(result)


@router.post("/save", dependencies=[Auth(scopes=["menus:save"])], response_model=ApiResponse)
@log_operation(log_message="目录/菜单/按钮", types=1)
async def menu_save(request: Request,
                    menu_data: MenuSchema,
                    db: AsyncSession = Depends(async_get_db)):
    """
    新增目录/菜单/权限
    :param request: 请求体
    :param menu_data: 菜单数据
    :param db: 数据库会话
    :return:
    """
    result = await MenuService.save_add_edit(db, menu_data)
    msg = f"新增{type_map[menu_data.types]}"
    if isinstance(result, bool) and result:
        return ApiResponse.success(f"{msg}成功")
    else:
        return ApiResponse.failed(f"{msg}失败！{result.get("message", "")}")


@router.put("/save", dependencies=[Auth(scopes=["menus:update"])], response_model=ApiResponse)
@log_operation(log_message="目录/菜单/按钮", types=2)
async def menu_update(request: Request, menu_data: MenuSchema, db: AsyncSession = Depends(async_get_db)):
    """
    编辑目录/菜单/权限
    :param request: 请求体
    :param menu_data: 菜单数据
    :param db: 数据库会话
    :return:
    """
    result = await MenuService.save_add_edit(db, menu_data)
    msg = f"编辑{type_map[menu_data.types]}"
    if isinstance(result, bool) and result:
        return ApiResponse.success(f"{msg}成功")
    else:
        return ApiResponse.failed(f"{msg}失败！{result.get("message", "")}")


@router.delete("/delete/{m_id}", dependencies=[Auth(scopes=["menus:delete"])], response_model=ApiResponse)
@log_operation(log_message="目录/菜单/按钮", types=3)
async def menu_delete(request: Request, m_id: Union[str, int], db: AsyncSession = Depends(async_get_db)):
    """
    删除目录/菜单/权限
    :param request: 请求体
    :param m_id: 目录/菜单/权限 id
    :param db: 数据库会话
    :return:
    """
    result = await MenuService.delete_menu(db, m_id)
    if result.get("error") == 0:
        return ApiResponse.success(result.get("message"))
    else:
        return ApiResponse.failed(result.get("message"))


@router.get("/menus_select", response_model=ApiResponse)
async def menus_select(db: AsyncSession = Depends(async_get_db)):
    """
    获取上级菜单
    :param db: 数据库会话
    :return:
    """
    result = await MenuService.get_menu_for_select(db)
    return ApiResponse.result(result)


@router.get("/get_permission",response_model=ApiResponse)
async def get_permission(db: AsyncSession = Depends(async_get_db)):
    """
    为角色菜单权限树形结构
    :param db: 数据库会话
    :return:
    """
    treeMenu = await MenuService.get_menu_permission_tree_for_role(db)
    return ApiResponse.result(treeMenu)
